package com.hx.miniblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hx.miniblog.exception.MiniBlogException;
import com.hx.miniblog.mapper.SysRoleMapper;
import com.hx.miniblog.pojo.SysRole;
import com.hx.miniblog.pojo.SysUser;
import com.hx.miniblog.mapper.SysUserMapper;
import com.hx.miniblog.pojo.ro.LoginRo;
import com.hx.miniblog.pojo.vo.LoginAccountVo;
import com.hx.miniblog.pojo.vo.LoginVo;
import com.hx.miniblog.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hx.miniblog.util.constant.Constant;
import com.hx.miniblog.util.constant.DatabaseConstant;
import com.hx.miniblog.util.constant.RedisKeyConstant;
import com.hx.miniblog.util.utils.JwtUtil;
import com.hx.miniblog.util.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * <p>
 * sys_user 服务实现类
 * </p>
 *
 * @author huwenhao
 * @since 2021-12-29
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 登录 暂时不做MD5
     * @param ro
     * @return
     */
    @Override
    public LoginVo login(LoginRo ro) {
        if (ro.validate()){
            SysUser sysUser = baseMapper.selectOne(new QueryWrapper<SysUser>().eq(DatabaseConstant.SysUserConstant.USER_NAME, ro.getUserName()));
            Optional.ofNullable(sysUser).ifPresentOrElse(user->{
                if (!user.getUserPassword().equals(ro.getPassword())){
                    throw new MiniBlogException(Constant.MESSAGE.PASSWORD_FALSE);
                }
            },()->{
                throw new MiniBlogException(Constant.MESSAGE.AUTH_USER_FAIL);
            });
            SysRole sysRole = roleMapper.selectOne(new QueryWrapper<SysRole>().eq(DatabaseConstant.SysRoleConstant.USER_ID, sysUser.getId()));


            return LoginVo.makeVo(sysUser,sysRole.getRoleType(),
                    jwtUtil.createToken(LoginAccountVo.makeVo(sysUser, sysRole.getRoleType())));
        }
        throw new MiniBlogException(Constant.MESSAGE.PARAM_ISNULL);
    }

    @Override
    public void logOut(LoginAccountVo vo) {
        if (redisUtil.hasKey(RedisKeyConstant.LOGIN_TOKEN+vo.getId())){
            redisUtil.del(RedisKeyConstant.LOGIN_TOKEN+vo.getId());
        }else {
            throw new MiniBlogException(Constant.MESSAGE.TOKEN_EXPIRE);
        }
    }
}
